$(function () {
    layui.use(['laytpl', 'laydate', 'table', 'form', 'formSelects', 'util', 'layer', 'soulTable', 'locals'], function () {
        var laytpl = layui.laytpl,
            laydate = layui.laydate,
            table = layui.table,
            form = layui.form,
            formSelects = layui.formSelects,
            util = layui.util,
            layer = layui.layer,
            soulTable = layui.soulTable,
            locals = layui.locals;
        var pageName = getPageName();
        var localParam = locals.get(pageName);
        var areaArr = [], allAreas = [], allMeters = [], myChart = null,
            tbHeigth = $('.center-part').height() - $('.charts').height() - 20,
            title = '', timer = null, tbIndex = null,
            resData = null, totalData = null, tbdata = null,
            max = util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');
        let totalLength = 0; // 水表总个数
        var param = {},
            datetype = {
                2: {type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss'},
                3: {type: 'date', format: 'yyyy-MM-dd'},
                4: {type: 'month', format: 'yyyy-MM'},
                5: {type: 'year', format: 'yyyy'}
            };
        var devTypeObj = {
            1: {name: '水', unit:'T'},
            0: {name: '电', unit:'kW·h'}
        };
        var currentTimeType = locals.get('currentTimeType') === null ? 0 : locals.get('currentTimeType');
        formSelects.btns('typeMenu', []);

        //初始化方法
        init();

        function init() {
            getAllAreas();
        }

        // 右侧查询按钮
        $(".refreshBtn").click(function () {
            $('.searchBtn').click();
        });

        //隐藏的提交事件
        $('.searchBtn').click(function () {
            form.on('submit(submitForm)', function (res) {
                var field = {
                    repType: param.repType,
                    startTime: res.field.startTime,
                    endTime: res.field.endTime,
                    areaId: res.field.areaId,
                    meterCodes: res.field.meterCodes,
                    deviceTypeCode: res.field.deviceTypeCode
                };
                let length = field.meterCodes.split(',').length;
                if(length > 0){
                    getChartDatas(field);
                }

                return false;
            });
        });

        //渲染 Totalbar
        function renderTotalBar(dataObj, title) {
            if (myChart != null && myChart != "" && myChart != undefined) { //判断是否已经存在myChart实例，有则销毁
                myChart.dispose();
            }
            myChart = echarts.init(document.getElementById('chartbox'), 'darkTheme'); //初始化myChart实例
            myChart.clear(); //清空当前实例
            var testdata = {
                xAxisBar: Object.keys(dataObj).map(function(val){
                    switch (param.repType) {
                        case '2':
                            return val.split(' ')[1];
                            break;
                        case '3':
                            return val.substr(5);
                            break;
                        default:
                            return val
                    }
                }),
                ydata: Object.values(dataObj).map(function(val){return val})
            };
            var barWidth = testdata.xAxisBar.length <= 7 ? 30 : 20;
            var bottomArr = []; // 柱底面
            for (let i = 0; i < testdata.xAxisBar.length; i++) {
                bottomArr.push(1)
            }
            var option = {
                title: {
                    text: title,
                    x: 'center'
                },
                backgroundColor: 'transparent',
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function (v) {
                        var s1 = v[1].marker + v[1].seriesName + ': ' + v[1].value;
                        return v[1].name + "<br>" + s1
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                dataZoom: [
                    {
                        show: true,
                        type: 'inside',
                        startValue: testdata.xAxisBar.length - 20,
                        endValue: testdata.xAxisBar.length
                    },
                    {
                        show: true,
                        startValue: testdata.xAxisBar.length - 20,
                        endValue: testdata.xAxisBar.length,
                        bottom: 10,
                        height: 10
                    }
                ],
                legend: {  //图示
                    type: 'scroll',
                    icon: 'roundRect',
                    selectedMode: false,
                    orient: 'vertical',
                    right: '3%',
                    top: 20,
                    bottom: 20,
                    pageIconSize: 10,
                    pageIconColor: '#eee',
                    pageIconInactiveColor: '#888',
                    pageTextStyle: {
                        color: '#eee'
                    },
                    data: ['总用量']
                },
                xAxis: [
                    {
                        name: '时间',
                        type: 'category',
                        data: testdata.xAxisBar,
                        axisTick: {
                            alignWithLabel: true,
                            inside: true
                        },
                        splitLine: {
                            show: true,
                            lineStyle: {
                                type: 'solid'
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        name: devTypeObj[param.deviceTypeCode].unit,
                        type: 'value',
                        max: 'dataMax',
                        splitLine: {    //网格线
                            show: true, //隐藏或显示
                            lineStyle: {
                                type: 'solid'    //设置网格线类型 dotted：虚线   solid:实线
                            }
                        },
                        axisTick: {
                            inside: true
                        },
                    }
                ],
                series: [
                    {
                        name: '总量1',
                        type: 'bar',
                        barWidth: barWidth,
                        data: testdata.ydata,
                        itemStyle: { // 用水量柱体颜色
                            color: {
                                x: 0, y: 1, x2: 1, y2: 1,
                                type: "linear",
                                global: false,
                                colorStops: [
                                    {offset: 0, color: "rgba(54, 202, 208, .8)"},
                                    {offset: 0.5, color: "rgba(54, 202, 208, .8)"},
                                    {offset: 0.5, color: "rgba(36, 131, 176, .8)"},
                                    {offset: 1, color: "rgba(36, 131, 176, .8)"}]
                            }
                        }
                    },
                    { // 顶
                        name: '总用量',
                        data: testdata.ydata,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        barGap: 0,
                        symbolPosition: "end",
                        symbol: "diamond",
                        symbolOffset: [0, "-50%"],
                        symbolSize: [barWidth, 12],
                        zlevel: 2,
                        itemStyle: {
                            color: '#0095e3' /* '#0095e3'*/
                        },
                    }
                ]
            };
            myChart.setOption(option);
        }

        function renderTable(data, strType) {
            if($('.layui-body').hasClass('iframe-layer')){
                tbHeigth = '400px';
                let h = $('.right-side-nav').height();
                $('.right-side-nav').height(h + 300)
            }
            $('.repTable').height(tbHeigth);
            let cols = [{field: "areaName", title: "区域", width: 130},
                {field: "anotherName", title: "设备", templet: '<div>{{d.anotherName}}</div>'},
                {field: "deviceTypeCode", title: "设备类型", width: 100,templet: function (d) {
                        return devTypeObj[param.deviceTypeCode].name + '表'
                    }},
                {
                    field: "detailDate", title: "日期", width: 170, templet: function (d) {
                        if(strType == 'total'){
                            if(param.repType == '2'){
                                return d.detailDate
                            }else {
                                return d.detailDate
                            }
                        }else{
                            var str = '';
                            switch (param.repType) {
                                case '2':
                                    str = d.detailDate;
                                    break;
                                case '3':
                                    str = d.day;
                                    break;
                                case '4':
                                    str = d.week + '周';
                                    break;
                                case '5':
                                    str = d.year;
                                    break;
                            }
                            return '<div>' + str + '</div>'
                        }
                    }
                },
            ];
            if(param.chartType == 'lineTrend') {
                // 趋势图，日累计用量、日累计标准
                cols.push({field: "standardSum", title: "日累计用量("+ devTypeObj[param.deviceTypeCode].unit +")"},
                    {field: "intervalQuantitySum", title: "日累计标准("+ devTypeObj[param.deviceTypeCode].unit +")"})
            }else{
                cols.push({field: "standard", title: "标准用量("+ devTypeObj[param.deviceTypeCode].unit +")"},
                    {field: "intervalQuantity", title: "实际用量("+ devTypeObj[param.deviceTypeCode].unit +")"})
            }
            tbIndex = table.render({
                elem: '#reports'
                , id: 'myTable'
                , data: data
                , height: tbHeigth
                , title: '报表'
                , initSort: {
                    field: 'detailDate' //排序字段，对应 cols 设定的各字段名
                    ,type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
                }
                , cols: [cols]
                , limit: data.length
                , loading: true
                , done: function () {
                    soulTable.render(this);
                }
            });
        }

        function getAllAreas() {
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allAreas = result;
                        var getTpl = $('#area-tpl').html();
                        laytpl(getTpl).render(result, function (html) {
                            $('.areaMenu').html(html);
                            formSelects.render('areaMenu');
                            formSelects.btns('areaMenu', ['remove'], {show: 'name', space: '10px'});
                            formSelects.value('areaMenu', 'val');
                            if(localParam){
                                param.area = localParam.area;
                                param.deviceTypeCode = localParam.deviceTypeCode;
                            }else{
                                areaArr = allAreas.map(function (item) {
                                    return item.areaId
                                });
                                param.area = areaArr;
                                param.deviceTypeCode = '0';
                            }
                            formSelects.value('areaMenu', param.area);
                            formSelects.value('typeMenu', [param.deviceTypeCode]);
                            getAllMeters();
                        });
                    }
                }
            });
        }

        function getAllMeters() {
            let type = param.deviceTypeCode == undefined ? '0' : param.deviceTypeCode;
            $.ajax({
                type: "post",
                url: ctx + "/meterManager/queryMeterByDevice.do",
                data: {
                    deviceTypeCode: type
                },
                dataType: "json",
                success: function (result) {
                    if (null != result) {
                        totalLength = result.length;
                        allMeters = result.sort(compare('areaId'));
                        param.meter = [];
                        // filterMeters(areaArr);
                        // getAllAreas();
                        let meters = [];
                        result.forEach(function (item) {
                            param.area.forEach(function (val) {
                                if(item.areaId == val){
                                    meters.push(item)
                                }
                            })
                        });
                        var getTpl = $('#meter-tpl').html();
                        laytpl(getTpl).render(meters, function (html) {
                            $('.meterMenu').html(html);
                            formSelects.render('meterMenu');
                            formSelects.btns('meterMenu', ['select', 'remove', 'reverse'], {
                                show: 'name',
                                space: '10px'
                            });
                            // formSelects.value('meterMenu', 'val');
                        });
                        if(localParam && localParam.meter.length > 0){
                            param.meter = localParam.meter;
                        }else{
                            param.meter = allMeters.map(function(item){
                                return item.meterCode
                            });
                        }
                        formSelects.value('meterMenu', param.meter);
                        locals.set(pageName, param);
                        // assignValue();
                        getLocalsParamData();
                    }
                }, error: function (e) {
                    layer.msg(result.message);
                }
            });
        }

        function filterMeters(areaArr) {
            var list = [], meters = [], typeMeter = [];
            allMeters.forEach(function (item) {
                areaArr.forEach(function (val) {
                    if (item.areaId == val) {
                        typeMeter.push(item);
                    }
                });
            });
            let typeMeterArr = typeMeter.filter(function (val) {
                return val.deviceTypeCode == param.deviceTypeCode
            });
            typeMeter.forEach(function (ite) {
                meters.push(ite.meterCode);
                list.push({"name": ite.areaName, "type": "optgroup"});
                list.push({"name": ite.anotherName, "value": ite.meterCode});
            });
            formSelects.data('meterMenu', 'local', {
                arr: uniqObjInArray(list)
            });
            formSelects.value('meterMenu', meters);
            param.area = [].concat(areaArr);
            param.meter = [].concat(meters);
            locals.set(pageName, param);
            if (timer) {
                clearTimeout(timer);
            }
            setTimeout(function () {
                $(".searchBtn").click();
            }, 0);
        }

        // 给筛选条件赋值
        function assignValue() {
            // 赋值
            form.val('submitForm', {
                repType: param.repType
            });
            form.val('chartRadio', {
                chartType: param.chartType
            });
            form.render('select');
            form.render('checkbox');
            form.render('radio');
            initDate(param.repType, param.dateObj[param.repType]);
            $('.refreshBtn').click();
        }

        function getLocalsParamData(){
            // 判断是否有缓存
            if (localParam) { // 有缓存
                param.repType = localParam.repType == undefined ? '2' : localParam.repType;
                if(localParam.dateObj){
                    param.dateObj = Object.assign({}, localParam.dateObj);
                }else{
                    param.dateObj = Object.assign({}, {
                        2: defaultSTimeETime(currentTimeType,'2'),
                        3: defaultSTimeETime(currentTimeType,'3'),
                        4: defaultSTimeETime(currentTimeType,'4'),
                        5: defaultSTimeETime(currentTimeType,'5')
                    });
                }
                param.chartType = localParam.chartType == undefined ? 'lineTrend' : localParam.chartType;
                $('[name="chartType"] option[value="'+ param.chartType +'"]').prop('checked',true);
                // param.deviceTypeCode = localParam.deviceTypeCode;
            } else { // 无缓存，初始化
                param.repType = $('.repType :selected').val();
                param.dateObj = Object.assign({}, {
                    2: defaultSTimeETime(currentTimeType,'2'),
                    3: defaultSTimeETime(currentTimeType,'3'),
                    4: defaultSTimeETime(currentTimeType,'4'),
                    5: defaultSTimeETime(currentTimeType,'5')
                });
                param.chartType = $('[name="chartType"]:checked').val();
                // 存
                locals.set(pageName, param);
            }
            assignValue();
        }

        // 监听区域多选
        formSelects.on('areaMenu', function (id, vals, val, isAdd, isDisabled) {
            areaArr.length = 0;
            areaArr = vals.map(function (item) {
                return item.value
            });
            filterMeters(areaArr);
        }, true);

        // 监听水电切换
        formSelects.on('typeMenu', function(id, vals, val, isAdd, isDisabled){
            if(vals.length === 0){
                layer.alert('请选择设备类型')
            }else{
                if(param.deviceTypeCode === val.value){
                    return false
                }else{
                    param.deviceTypeCode = val.value;
                    if (myChart != null && myChart != "" && myChart != undefined) { //判断是否已经存在myChart实例，有则销毁
                        // myChart.dispose();
                        myChart.clear();
                    }
                    renderTable([], 'total');
                    param.meter = [];
                    locals.set(pageName, param);
                    localParam = locals.get(pageName);
                    getAllMeters();
                }
            }
        }, true);

        // 监听设备select是否展开
        let meterMenuIsOpen = false;
        formSelects.opened('meterMenu', function(id){
            meterMenuIsOpen = true;
        });
        formSelects.closed('meterMenu', function(id){
            meterMenuIsOpen = false;
        });
        // 监听鼠标在设备select中是否点击，无点击后延迟500ms发送查询请求
        $(".dev-option-wrap").on('mouseup','.xm-select-dl',function(event){
            if(meterMenuIsOpen){
                if(event.button == 0){
                    //鼠标左键
                    setTimeout(function () {
                        let valArr = formSelects.value('meterMenu');
                            if(valArr.length > 0){
                                $('.tips').addClass('layui-hide');
                                $(".refreshBtn").click();
                            }else{
                                $('.tips').removeClass('layui-hide');
                            }
                    },500)
                }
            }
        });

        // 监听报表类型，重新渲染时间选择器
        form.on('select(repType)', function (data) {
            param.repType = data.value;
            $('#startTime').remove();
            $('.startTime').html('<input type="text" class="layui-input" id="startTime" name="startTime">');
            $('#endTime').remove();
            $('.endTime').html('<input type="text" class="layui-input" id="endTime" name="endTime">');
            form.render('checkbox');
            locals.set(pageName, param);
            initDate(param.repType, param.dateObj[param.repType]);
            $('.refreshBtn').click();
        });

        // 监听line、bar切换
        form.on('radio(chartType)', function (data) {
            param.chartType = data.value;
            locals.set(pageName, param);
            $('.searchBtn').click();
        });

        function initDate(repType, dateArr) {
            // console.log(dateArr[0])
            var start = laydate.render({
                elem: "#startTime",
                value: dateArr[0],
                type: datetype[repType].type,
                format: datetype[repType].format,
                trigger: 'click',
                min: minDate(repType),
                max: max,
                done: function (value) {
                    var se = defaultSTimeETime(currentTimeType,repType, value);
                    // console.log(se)
                    $('#startTime').val(se[0]);
                    $('#endTime').val(se[1]);
                    param.dateObj[repType][0] = se[0];
                    param.dateObj[repType][1] = se[1];
                    locals.set(pageName, param);
                    $('.searchBtn').click();
                }
            });
            $('#endTime').val(defaultSTimeETime(currentTimeType,repType, dateArr[0])[1]);
        }

        function getChartDatas(datas) {
            var loadIdx = null;
            $.ajax({
                type: "post",
                url: ctx + "/waterChart/queryForChart1.do",
                data: datas,
                async: true,
                cache: false,
                dataType: "json",
                beforeSend: function(){
                    loadIdx = layer.load(1);
                },
                success: function (result) {
                    if (result.code == "000000") {
                        resData = result.data.detail;
                        totalData = result.data.total;
                        let str = '用' + devTypeObj[param.deviceTypeCode].name;
                        if (datas.repType == 2) {
                            title = $('#startTime').val().split(' ')[0] + str + '统计表';
                        } else if (datas.repType == 3) {
                            title = $('#startTime').val().substring(0, 7) + str + '统计表';
                        } else {
                            title = $('#startTime').val() + str + '统计表';
                        }
                        let checkedMeter = datas.meterCodes.split(',').length;
                        if(param.chartType == 'bar'){
                            renderTotalBar(totalData, title);
                            // table 数据
                            let tbList = [];
                            for(let k in totalData){
                                tbList.push({
                                    areaName: formSelects.value('areaMenu','nameStr'),
                                    anotherName: '全部',
                                    detailDate: k,
                                    standard: null,
                                    intervalQuantity: totalData[k]
                                });
                            }
                            renderTable(tbList, 'total');
                        }else{
                            tbdata = [].concat.apply([], Object.values(resData));
                            renderTable(tbdata,'detail');
                            renderLine(resData, title);
                        }
                    } else {
                        layer.msg(result.message);
                    }
                },
                complete: function () {
                    layer.close(loadIdx);
                }
            });
        }

        //渲染line
        function renderLine(dataList, title) {
            if (myChart != null && myChart != "" && myChart != undefined) { //判断是否已经存在myChart实例，有则销毁
                myChart.dispose();
            }
            myChart = echarts.init(document.getElementById('chartbox'), 'darkTheme'); //初始化myChart实例
            myChart.clear(); //清空当前实例

            var colors = ['#0090ff',   '#009db2', '#bf19ff','#02cdff',
                 '#854cff', '#5f45ff', '#f9e264',
                '#0780cf',  '#f47a75','#da9e27'];
            var xAxisArr = Object.keys(dataList); // 横坐标 -日期
            var dataArr = transArr(Object.values(dataList));
            var data = []; // 纵坐标 - 数值
            if(param.chartType === 'line'){
                for (var i = 0; i < dataArr.length; i++) {
                    let res = formatData(dataArr[i], 'intervalQuantity');
                    if(res.allNull){
                        data.push({
                            name: dataArr[i][0].anotherName,
                            type: 'line',
                            data: res.data
                        })
                    }else{
                        data.push({
                            name: dataArr[i][0].anotherName,
                            type: 'line',
                            areaStyle: {
                                opacity: 0.8,
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: colors[i % 10]
                                }, {
                                    offset: 1,
                                    color: 'transparent'
                                }])
                            },
                            data: res.data
                        })
                    }
                }
            }else if(param.chartType === 'lineTrend') {
                for (var i = 0; i < dataArr.length; i++) {
                    let resQuantity = formatData(dataArr[i], 'intervalQuantitySum');
                    let resStandard = formatData(dataArr[i], 'standardSum');
                    if(resQuantity.allNull){
                        data.push({
                            name: dataArr[i][0].anotherName + '日累计用量',
                            type: 'line',
                            data: resQuantity.data
                        },{
                            name: dataArr[i][0].anotherName + '日累计标准',
                            type: 'line',
                            data: resStandard.data,
                            color: 'red'
                        })
                    }else{
                        data.push({
                            name: dataArr[i][0].anotherName + '日累计用量',
                            type: 'line',
                            areaStyle: {
                                opacity: 0.8,
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: colors[i % 10]
                                }, {
                                    offset: 1,
                                    color: 'transparent'
                                }])
                            },
                            data: resQuantity.data
                        },{
                            name: dataArr[i][0].anotherName + '日累计标准',
                            type: 'line',
                            data: resStandard.data,
                            color: 'red'
                        })
                    }
                }
            }

            var option = {
                backgroundColor: 'transparent',
                color: colors,
                title: {
                    text: title,
                    x: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(18,37,79,.5)',
                    textStyle: {
                        color: '#fff'
                    },
                    confine: true,
                    padding: [10, 10],
                    extraCssText: 'border:1px solid #3398DB ;box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)'
                },
                legend: {
                    type: 'scroll',
                    icon: 'pin',
                    selectedMode: false,
                    // orient: 'vertical',
                    left: '8%',
                    top: 20,
                    bottom: 20,
                    pageIconSize: 10,
                    pageIconColor: '#eee',
                    pageIconInactiveColor: '#888',
                    pageTextStyle: {
                        color: '#eee'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                dataZoom: [
                    {
                        show: true,
                        type: 'inside',
                        startValue: xAxisArr.length - 20,
                        endValue: xAxisArr.length
                    },
                    {
                        show: true,
                        startValue: xAxisArr.length - 20,
                        endValue: xAxisArr.length,
                        bottom: 10,
                        height: 10
                    }
                ],
                xAxis: [
                    {
                        name: '时间',
                        type: 'category',
                        boundaryGap: false,
                        data: xAxisArr.map(function (str) {
                            if (param.repType == 2) {
                                return str.split(' ')[1].slice(0,5);
                            } else if (param.repType == 4) {
                                return str + '周'
                            } else {
                                return str
                            }
                        })
                    }
                ],
                yAxis: [
                    {
                        name: devTypeObj[param.deviceTypeCode].unit,
                        type: 'value',
                        max: 'dataMax'
                    }
                ],
                series: data
            };
            // console.log(JSON.stringify(option));
            myChart.setOption(option);
        }

        // 导出excel
        $('.exportBtn').click(function () {
            // 导出图片
            downloadAsImg();
            // 导出表格
            soulTable.export('myTable', {filename: title + '.xlsx'});
        });

        function downloadAsImg() {
            var mycanvas = $("#chartbox").find("canvas")[0];
            if (mycanvas == undefined) {
                layer.msg("尚未生成图表！");
            } else {
                var image = mycanvas.toDataURL("image/jpeg");
                var $a = document.createElement('a');
                $a.setAttribute("href", image);
                $a.setAttribute("download", title + ".jpg");
                $a.click();
            }
        }

        window.addEventListener("resize", function () {
            if (myChart != null) {
                myChart.resize();
            }
            // table rsize height
            tbHeigth = $('.center-part').height() - $('.charts').height() - 20;
            $('.repTable').height(tbHeigth);
            $('.layui-table-view').height(tbHeigth);
            // $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
            // $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
        });

        // 二维数组取最大值
        function getMaxOfArray(arr, field) {
            var temp = [];
            if (field) {
                arr.forEach(item => {
                    item.forEach((v) => {
                        temp.push(v[field])
                    });
                });
            } else {
                temp = [].concat.apply([], arr);
            }
            return Math.max.apply(null, temp);
        }

        function figureMax(val) {
            return val <= 10 ? Math.ceil(val) + 1 : Math.ceil(val / 10 + 0.01) * 10
        }

        // 多个数组，按索引值重组
        function transArr(arr) {
            let res = [];
            arr.forEach(item => {
                item.forEach((d, i) => {
                    let a = res[i] = res[i] || []
                    a.push(d)
                })
            });
            return res
        }

        // 数据处理
        function formatData(arr, key) {
            var res = [];
            var num = 0;
            arr.forEach(function (item) {
                if(item[key] == null){
                    res.push(item[key]);
                    num++;
                }else{
                    res.push(item[key]);
                }
            });
            return {data: res, allNull: num == arr.length}
        }

        /* 获取不同报表的选择范围
        *  parm : type   报表类型
        *  2日： 24小时24条数据， 可选3个月
        *  3周： 一周7天7条数据， 可选2年
        *  4月： 一个月4周（或5周）一周一条数据， 可选2年
        *  5年： 一年12个月，一个月一条数据，可选2年
        * */
        function minDate(type) {
            var min = '';
            if (type == 2) {
                min = GetPreMonthDay(2);
            } else {
                var year = new Date().getFullYear() - 2;
                min = year + '-01-01 00:00:00'
            }
            return min;
        }

        /* 日期向前推 m 个月
        *  param： date : yyyy-MM-dd HH:mm:ss
        *  返回值： 前m个月1号0点
        *  */
        function GetPreMonthDay(m) {
            var preYear = 0;
            var resultDate, year, month, day;
            var currDate = new Date();
            year = currDate.getFullYear();
            month = currDate.getMonth() + 1;
            day = currDate.getDate();
            var days = new Date(year, month, 0);
            days = days.getDate(); //获取当前日期中月的天数
            var year2 = year;
            var month2 = parseInt(month) - m;
            if (month2 <= 0) {
                preYear = parseInt(m / 12);
                year2 = parseInt(year2 - preYear);
                month2 = 12 - (Math.abs(month2) % 12);
            }
            var day2 = day;
            var days2 = new Date(year2, month2, 0);
            days2 = days2.getDate();
            if (day2 > days2) {
                day2 = days2;
            }
            if (month2 < 10) {
                month2 = '0' + month2;
            }
            // resultDate = year2 + '-' + month2 + '-' + day2;
            resultDate = year2 + '-' + month2 + '-01 00:00:00';
            return resultDate;
        }

        // 打印
        $('.printBtn').click(function () {
            createPrintTable();
            var timer = null;
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",
                    "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
                    "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
                    "thead tr th:first-child,tbody tr td:first-child{width:80px}",
                    "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", "img.chartImg{width: 100%;margin-bottom:10px;}", "</style>"].join(""),
                printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
                // 获取图片
                chartImg = $('<img class="chartImg" src="' + $("#chartbox").find("canvas")[0].toDataURL("image/jpeg") + '">');
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
            printHtml.find("th.layui-table-patch").remove();
            printHtml.find(".layui-table-col-special").remove();
            doc.write(style + chartImg.prop("outerHTML") + printHtml.prop("outerHTML"));
            iframe.contentWindow.focus();
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(function () {
                iframe.contentWindow.print();
                iframe.remove();
                $('#printContentBox').empty();
            }, 0)
        });

        function createPrintTable() {
            $('#printContentBox').html('<table id="printTb"></table>');
            var temp = tbIndex.config;
            table.render({
                elem: '#printTb'
                , data: temp.data
                , cellMinWidth: 48
                , size: 'sm'
                , defaultToolbar: []
                , cols: temp.cols
                , limit: temp.data.length
            })
        }

    });
});
